package jrain.fw.script.core;

import java.text.MessageFormat;
import java.util.Map;

import jrain.fw.script.context.ScriptContext;
import jrain.fw.script.operator.Constants;
import jrain.fw.script.resolver.BaseResolver;
import jrain.fw.script.tools.ELException;
import jrain.fw.script.tools.ScriptException;

public class Evaluator implements ExpressionEvaluator {

	static ELEvaluator sEvaluator = new ELEvaluator(new BaseResolver());

	public String validate(String pAttributeValue) {
		try {
			sEvaluator.setBypassCache(true);
			sEvaluator.parseExpressionString(pAttributeValue);
			sEvaluator.setBypassCache(false);
			return null;
		} catch (ELException exc) {
			return MessageFormat.format(Constants.ATTRIBUTE_PARSE_EXCEPTION, pAttributeValue, exc.getMessage());
		}
	}

	public Object evaluate(String pAttributeValue, Class<?> pExpectedType, ScriptContext pPageContext, Map<Object, Object> functions, String defaultPrefix)
			throws ScriptException {
		try {
			return sEvaluator.evaluate(pAttributeValue, pPageContext, pExpectedType, functions, defaultPrefix);
		} catch (ELException exc) {
			throw new ScriptException(MessageFormat.format(Constants.ATTRIBUTE_EVALUATION_EXCEPTION, pAttributeValue, exc.getMessage(), exc.getRootCause()),
					exc.getRootCause());
		}
	}

	public Object evaluate(String pAttributeValue, Class<?> pExpectedType, ScriptContext pPageContext) throws ScriptException {
		return evaluate(pAttributeValue, pExpectedType, pPageContext, null, null);
	}

	public static String parseAndRender(String pAttributeValue) throws ScriptException {
		try {
			return sEvaluator.parseAndRender(pAttributeValue);
		} catch (ELException exc) {
			throw new ScriptException(MessageFormat.format(Constants.ATTRIBUTE_PARSE_EXCEPTION, "test", "" + pAttributeValue, exc.getMessage()));
		}
	}

}
